package com.zuorenke.exception;

import com.zuorenke.model.constants.Constants;
import com.zuorenke.model.Performer;
import com.zuorenke.model.Result;
import io.vertx.core.http.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Z.R.K
 * @description
 * @create 2019-05-17 16:49:19
 **/
@Component
@Slf4j
public class ExceptionPerformer implements InitializingBean {
	
	public Performer notFoundPerformer;
	
	public Performer methodNotSupportPerformer;
	
	public Result notFound() {
		Result result = new Result();
		result.setSuccess(false);
		result.setCode(404);
		result.setMsg("not found!");
		return result;
	}
	
	public Result methodNotSupport(HttpMethod method) {
		Result result = new Result();
		result.setSuccess(false);
		result.setCode(405);
		result.setMsg("Request method " + method + " not supported!");
		return result;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		notFoundPerformer = new Performer();
		methodNotSupportPerformer = new Performer();
		notFoundPerformer.setBean(this);
		methodNotSupportPerformer.setBean(this);
		List<Class> paramClasses = new ArrayList<>();
		paramClasses.add(HttpMethod.class);
		List<String> paramNames = new ArrayList<>();
		paramNames.add("method");
		List<Type> paramTypes = new ArrayList<>();
		paramTypes.add(HttpMethod.class);
		List<Annotation[]> paramAnnos = new ArrayList<>();
		paramAnnos.add(new Annotation[0]);
		try {
			notFoundPerformer.setMethod(this.getClass().getMethod(Constants.NOTFOUND_METHOD));
			methodNotSupportPerformer.setMethod(this.getClass().getMethod(Constants.NOTSUPPORT_METHOD, HttpMethod.class));
			methodNotSupportPerformer.setParamTypes(paramTypes);
			methodNotSupportPerformer.setParamClasses(paramClasses);
			methodNotSupportPerformer.setParamNames(paramNames);
			notFoundPerformer.setParamAnnos(paramAnnos);
			methodNotSupportPerformer.setParamAnnos(paramAnnos);
		} catch (NoSuchMethodException e) {
			log.error("NoSuchMethodException {}", e);
		}
	}
}
